<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 左侧角色列表 -->
      <el-col :span="10">
        <el-collapse-transition>
          <el-card v-show="isFilterVisible" class="search-wrapper">
            <el-form :inline="true" :model="staffQuery">
              <el-form-item label="用户名称">
                <el-input
                  v-model="staffQuery.name"
                  clearable
                  placeholder="请输入用户名称"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-collapse-transition>
        <el-card class="box-card">
          <!-- 搜索区域 -->
          <div class="table-operations">
            <el-button
              type="primary"
              size="small"
              class="filter-trigger"
              @click="isFilterVisible = !isFilterVisible"
            >{{ isFilterVisible ? "收起" : "检索" }}
              <i
                :class="[
                  'el-icon-arrow-down',
                  { 'is-reverse': isFilterVisible },
                ]"
              />
            </el-button>
            <!-- <el-button
              type="success"
              size="small"
              icon="el-icon-plus"
              @click="handleAddRole"
              >新增角色</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEditRole"
              >编辑角色</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDeleteRole"
              >删除角色</el-button
            > -->
          </div>
          <el-table
            :data="userList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="用户名称" />
            <el-table-column prop="mobile" label="手机号" />
            <el-table-column prop="parent" label="所属部门">
              <template slot-scope="scope">
                <span>{{
                  scope.row.parentName ? scope.row.parentName : "无"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleSetPermission(scope.row)"
                >去设置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              :current-page="staffQuery.page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="staffQuery.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧权限设置 -->
      <el-col :span="14">
        <el-card class="box-card">
          <div slot="header">
            <span>{{ currentRole.name || "请选择用户" }}</span>
          </div>

          <el-table
            ref="menuTable"
            :data="roleListDetails"
            style="width: 100%"
            row-key="roleId"
          >
            <el-table-column label="角色名称" min-width="180">
              <template slot-scope="scope">
                <span>{{ scope.row.roleName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="权限" width="120" align="right">
              <template slot-scope="scope">
                <div class="checkbox-container">
                  <el-checkbox
                    v-model="scope.row.status"
                    :true-label="1"
                    :false-label="0"
                    @change="() => handleCheckboxChange(scope.row)"
                  >拥有</el-checkbox>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增角色对话框 -->
    <el-dialog
      :title="roleForm.id ? '编辑角色' : '新增角色'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="是否可删除" prop="isDelete">
          <el-radio-group v-model="roleForm.isDelete">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selStaffListApi,
  selUserRoleListByUserIdApi,
  addUserRoleApi,
  delUserRoleByIdApi
} from '@/api/system'
export default {
  name: 'UserManagement',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 角色列表
      roleList: [],
      // 总条数
      total: 0,
      // 当前选中的角色
      currentRole: {},
      // 权限树数据
      permissionList: [
        {
          id: '1',
          label: '首页-1',
          show: true
        },
        {
          id: '100',
          label: '系统管理-100',
          children: [
            {
              id: '100-1',
              label: '用户管理-100',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            },
            {
              id: '110',
              label: '角色管理-110',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isFilterVisible: false,
      // 角色列表参数
      roleListParams: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      currentRoleId: '', // 当前选中的角色id

      // 新增对话框可见性
      dialogVisible: false,

      // 角色表单数据
      roleForm: {
        id: '', // id存在表示编辑，不存在表示新增
        name: '',
        isDelete: 1,
        remark: ''
      },
      roleListDetails: [], // 角色列表详情
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 50, message: '角色名称不能超过50个字符', trigger: 'blur' }
        ],
        number: [{ required: true, message: '请输入编号', trigger: 'blur' }]
      },

      // 新增的 selectedIds 和 currentRole 属性
      selectedIds: [], // 当前选中的菜单id
      // 用户列表参数
      userListParams: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      userList: [], // 用户列表
      // 职员列表
      staffQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        mobile: '',
        parent: ''
      },
      directorList: [] // 职员列表
    }
  },
  created() {
    this.selStaffList()
  },
  methods: {
    // 职工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery)
      this.userList = res.records || []
      this.total = res.total
    },
    // 分页
    handleCurrentChange(page) {
      console.log(page)
      this.staffQuery.page = page
      this.selStaffList()
    },
    // 分页
    handleSizeChange(pageSize) {
      this.staffQuery.pageSize = pageSize
      this.selStaffList()
    },
    // 查询
    handleQuery() {
      this.staffQuery.page = 1
      this.selStaffList()
    },
    // 重置
    resetQuery() {
      this.staffQuery = {
        page: 1,
        pageSize: 10,
        name: '',
        mobile: '',
        parent: ''
      }
      this.selStaffList()
    },
    // 设置权限
    async handleSetPermission(row) {
      // 设置当前选中的用户
      this.currentRole = row

      try {
        // 调用API获取用户角色列表
        const res = await selUserRoleListByUserIdApi(row.id)
        // 处理返回的数据
        if (res.data && Array.isArray(res.data)) {
          this.roleListDetails = res.data
        } else {
          this.roleListDetails = []
          this.$message.warning('获取用户权限列表为空')
        }
      } catch (error) {
        console.error('获取用户权限列表失败', error)
        this.$message.error('获取用户权限列表失败')
        this.roleListDetails = []
      }
    },

    // 复选框变更处理
    async handleCheckboxChange(row) {
      try {
        if (row.status === 1) {
          // 状态为1，调用新增接口
          const params = {
            roleId: row.roleId,
            userId: row.userId // 当前选中用户的ID
          }
          const res = await addUserRoleApi(params)
          if (res.code === 1) {
            this.$message.success('角色分配成功')
          } else {
            // API返回失败，回滚复选框状态
            row.status = 0
            this.$message.error(res.msg || '角色分配失败')
          }
        } else {
          // 状态为0，调用删除接口
          // 假设需要用户角色关系ID，这里可能需要根据实际情况调整
          const params = {
            roleId: row.roleId,
            userId: row.userId
          }
          const res = await delUserRoleByIdApi(params)
          if (res.code === 1) {
            this.$message.success('角色移除成功')
          } else {
            // API返回失败，回滚复选框状态
            row.status = 1
            this.$message.error(res.msg || '角色移除失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        // 发生错误，回滚复选框状态
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('操作失败，请重试')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.permission-options {
  display: flex;
  gap: 15px;
}

.permission-options .el-checkbox {
  margin-right: 0;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 120px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.33%;
}

.menu-permissions {
  padding: 20px;
}

.menu-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.permission-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.permission-item {
  display: flex;
  align-items: center;
  width: calc(33.33% - 14px);
  min-width: 200px;
}

.permission-name {
  margin-right: 10px;
  color: #606266;
}

.permission-checkbox {
  margin-left: auto;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 60px;
  border-bottom: 1px solid #ebeef5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-name {
  color: #606266;
}

.sub-menu-list {
  width: 100%;
}

.sub-menu-item {
  width: 100%;
}

.menu-row {
  display: flex;
  width: 100%;
  border-bottom: 1px solid #ebeef5;
  padding: 10px 0;
}

.menu-column {
  flex: 1;
  text-align: left;
  padding-left: 20px;
}

.permission-column {
  width: 120px;
  text-align: center;
}

.menu-name {
  display: flex;
  align-items: center;
}

.menu-name.third-level {
  padding-left: 20px;
}

.third-level-menu {
  width: 100%;
}

.el-icon-arrow-right {
  margin-right: 5px;
  transition: transform 0.3s;
}

.el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 调整展开图标的位置 */
.el-table__expand-icon {
  display: none;
}

.menu-name-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.menu-name-cell .el-icon-arrow-right {
  margin-right: 8px;
  transition: transform 0.3s;
}

.menu-name-cell .el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 隐藏表格默认的展开图标列 */
.el-table__expand-column {
  display: none;
}

/* 移除展开行的默认内边距 */
.el-table__expanded-cell {
  padding: 0 !important;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

.menu-name.third-level {
  padding-left: 20px;
}

.menu-name.fourth-level {
  padding-left: 40px;
}

.fourth-level-menu {
  width: 100%;
  padding-left: 20px;
}

/* 使用绝对定位确保对齐 */
.checkbox-container {
  position: relative;
  width: 100%;
  height: 100%;
}

:deep(.el-checkbox) {
  position: absolute;
  right: 20px; /* 调整此值以匹配权限标题位置 */
  top: 50%;
  transform: translateY(-50%);
}
</style>
